/**
 * 抓取屏幕，并进行打包，发送的服务器端
 * 继承自TimerTask，间隔性抓取屏幕，对图像数据压缩后，打包发送
 */
package com.jahentao.integrationTest.case03.common;

import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.TimerTask;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.imageio.ImageIO;

public class ScreenCapture extends TimerTask{
	
	public final static int width;
	public final static int height;

	private String ip;
	
	public ScreenCapture(String ip){
		this.ip = ip;
	}
	
	static{
		Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();
		width = (int)screensize.getWidth();
		height = (int)screensize.getHeight();
	}
	
	@Override
	public void run() {
		// 用一个定时器，每间隔 捕获一次屏幕
		try {
			long time = System.currentTimeMillis();
			// 截取全屏数据				
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			ZipOutputStream zos = new ZipOutputStream(baos);
			//压缩条目
			ZipEntry entry = new ZipEntry(time+"");
			//添加一个压缩条目
			zos.putNextEntry(entry);
			//压缩图像数据
			captureImage(new Rectangle(0, 0, width, height),zos);
			zos.close();
			baos.close();
			
			byte[] data = baos.toByteArray();
			
			int count = data.length/(1024*60) + 1;
			
			// 打包策略是打包5份 每份大概60k
			for(int i=0; i<count; i++){
				Packet pack = new Packet(time, count, i, data);
				pack.packDatagram(ip).send();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 获取屏幕指定区域的截图
	 */
	public void captureImage(Rectangle rectangle, OutputStream os){
		try {
			Robot robot = new Robot();
			BufferedImage bi = robot.createScreenCapture(rectangle);
			ImageIO.write(bi, "jpg", os);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
